package com.insis.manager;

import com.insis.loadBalance.RoundRobinRule;
import com.insis.message.RpcRequestMessage;
import com.insis.protocol.MessageCodecSharable;
import com.insis.protocol.ProcotolFrameDecoder;
import com.insis.protocol.SequenceIdGenerator;
import com.insis.registry.NacosServerDiscover;
import com.insis.server.handler.RpcResponseMessageHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;

@Slf4j
public class RpcClientManager {

    private static String ip;
    private static int port;
    private static Channel channel = null;
    private static final Object LOCK = new Object();

    public RpcClientManager(){
        NacosServerDiscover nacosServerDiscover = new NacosServerDiscover(new RoundRobinRule());
        InetSocketAddress service = nacosServerDiscover.getInstance("queryMoneyService");
        ip = service.getHostName();
        port = service.getPort();
    }

    public <T> T getProxyService(Class<T> serviceClass){
        ClassLoader loader = serviceClass.getClassLoader();
        Class<?>[] interfaces = new Class[]{serviceClass};
        //Class<?>[] interfaces = serviceClass.getInterfaces();
        Object o = Proxy.newProxyInstance(loader, interfaces, ((proxy, method, args) -> {
            //1.将方法的调用，转换为消息对象
            int i = SequenceIdGenerator.nextId();
            RpcRequestMessage message = new RpcRequestMessage(
                    i,
                    serviceClass.getName(),
                    method.getName(),
                    method.getReturnType(),
                    method.getParameterTypes(),
                    args
            );
            //2.将消息对象发送出去
            getChannel().writeAndFlush(message);
            //3.准备一个空promise对象
            DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());//指定promise对象异步接收结果的线程
            RpcResponseMessageHandler.PROMISES.put(i, promise);
            //4.等待promise结果
            promise.await();
            if(promise.isSuccess()){
                return promise.getNow();
            }else{
                throw new RuntimeException(promise.cause());
            }
        }));
        return (T) o;
    }


    public static Channel getChannel(){
        if (channel != null){
            return channel;
        }
        synchronized (LOCK){
            if(channel != null){
                return channel;
            }
            initChannel();
            return channel;
        }
    }

    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProcotolFrameDecoder());
                ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                ch.pipeline().addLast(RPC_HANDLER);
            }
        });
        try {
            channel = bootstrap.connect(ip, port).sync().channel();
            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (Exception e) {
            log.error("client error", e);
        }
    }
}
